package com.gict.antifraudback.interceptor;


import cn.hutool.core.util.StrUtil;
import com.gict.antifraudback.entity.User;
import com.gict.antifraudback.service.UserService;
import com.gict.antifraudback.utils.NoAuthorization;
import com.gict.antifraudback.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 前台登录拦截器
 *
 * @author 18239
 */
@Component
public class FrontTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        if (((HandlerMethod) handler).hasMethodAnnotation(NoAuthorization.class)) {
            return true;
        }

        String token = request.getHeader("accessToken");

        if (StrUtil.isNotEmpty(token)) {
            try {
                User user = this.userService.frontQueryUserByToken(token);
                //将user放入threadLocal
                if (null != user) {
                    UserThreadLocal.set(user);
                    return true;
                }
            } catch (Exception e) {
                response.setStatus(401);
                return false;
            }
        }
        response.setStatus(401);
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //从threadLocal中移除user
        UserThreadLocal.remove();

    }
}
